﻿using System;
using System.Data;
using System.Net.Mail;
using MailClient.Data;
using MailClient.Handlers;

namespace MailClient.Commands
{
    class Merch : Query, ICommand, IDisposable
    {
        #region private variables
        private Handlers.designator _designator;
        private bool revised;
        private string status;
        private string[] EmailBody;
        private int storenum;
        private string preid;
        private string pwoid;
        private string otpid;
        private string otbid;
        private bool rev;
        private string revid;
        private string finid;
        private string city;
        private string comment;
        private StoresType StoreType;
        private string carpet;
        private string power;
        private string ordercopy;
        #endregion

        #region public properties
        public Handlers.designator Designator
        {
            get { return _designator; }
            set { _designator = Designator; }
        }

        public bool IsRevised { get { return revised; } }

        public string Status
        {
            get { return status; }
            set { status = value; }
        }

        public int StoreNumber { get { return storenum; } }
        public string PreId { get { return preid; } }
        public string PwoId { get { return pwoid; } }
        public string OtpId { get { return otpid; } }
        public string OtbId { get { return otbid; } }
        public string RevId { get { return revid; } }
        public string FinalId { get { return finid; } }
        public string Comment { get { return comment; } }
        public string OrderCopy { get { return ordercopy; } }
        public string PowerPlan { get { return power; } }
        public string CarpetPlan { get { return carpet; } }

        public Merch(Command com, string[] query) { _query = query; }
        #endregion

        #region Interface methods
        private string[] _query;

        public void Dispose() { }

        /// <summary>
        /// This processes the email body currently only works for wal-mart format emails
        /// </summary>
        /// <param name="job"></param>
        private void Process(ref Job job)
        {
            string s = ":";
            string t = string.Empty;
            foreach (string i in EmailBody)
            {
                if (i.Contains("Store Number:", StringComparison.CurrentCultureIgnoreCase))
                {
                    int n = parsenumber(i, "Store Number:");
                    if (n != 0) storenum = n;
                }
                else if (i.Contains("City:", StringComparison.CurrentCultureIgnoreCase)) city = Test(i, s);
                else if (i.Contains("Project Type:", StringComparison.CurrentCultureIgnoreCase)) StoreType = ToStoreType(Test(i, s));
                else if (i.Contains("Project Status:", StringComparison.CurrentCultureIgnoreCase))
                {
                    // this can also say carpet plan or order copy
                    status = Test(i, s);
                    if (i.Contains("Revised", StringComparison.CurrentCultureIgnoreCase))
                        rev = true;
                    if (i.Contains("Carpet Plan", StringComparison.CurrentCultureIgnoreCase))
                    {
                        carpet = job.DateReceived.ToShortDateString();
                    }
                    if (i.Contains("Order Copy", StringComparison.CurrentCultureIgnoreCase))
                    {
                        ordercopy = job.DateReceived.ToShortDateString();
                    }
                    if (i.Contains("Power Plan", StringComparison.CurrentCultureIgnoreCase))
                    {
                        power = job.DateReceived.ToShortDateString();
                    }
                }
                // comments often follow on the next line '\r\n' deal with it
                else if (i.Contains("Comments:", StringComparison.CurrentCultureIgnoreCase)) comment = Test(i, s);
                else if (i.Contains("PRE ID", StringComparison.CurrentCultureIgnoreCase))
                {
                    t = Test(i, s);
                    if (t != string.Empty) preid = DoString(t);
                }
                else if (i.Contains("PWO ID", StringComparison.CurrentCultureIgnoreCase))
                {
                    t = Test(i, s);
                    if (t != string.Empty) pwoid = DoString(t);
                }
                else if (i.Contains("OTP ID", StringComparison.CurrentCultureIgnoreCase))
                {
                    t = Test(i, s);
                    if (t != string.Empty) otpid = DoString(t);
                }
                else if (i.Contains("OTB ID", StringComparison.CurrentCultureIgnoreCase))
                {
                    t = Test(i, s);
                    if (t != string.Empty) otbid = DoString(t);
                }
                else if (i.Contains("REV ID", StringComparison.CurrentCultureIgnoreCase))
                {
                    t = Test(i, s);
                    if (t != string.Empty) revid = DoString(t);
                }
                else if (i.Contains("FIN ID", StringComparison.CurrentCultureIgnoreCase))
                {
                    t = Test(i, s);
                    if (t != string.Empty) finid = DoString(t);
                }
                t = string.Empty;
            }
        }

        private MailMessage _msg;

        public MailMessage MsgReply
        {
            get { return _msg; }
        }

        public bool Command(Job job)
        {

            try
            {
                EmailBody = job.MessageBody.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                Process(ref job);
                return true;
            }
            catch
            {
                return false;
            }
        }

        public bool CommitData()
        {
            try
            {
                /*
                * merch colmun names: `merch`.`id`, `merch`.`trident_id`, `merch`.`Pre_PWO`, `merch`.`PWO`, `merch`.`OTP`, `merch`.`OTB`, `merch`.`Final`, `merch`.`Revised_Final`, `merch`.`Order_Copy`
                * 
                * shell column names: `shell`.`id`, `shell`.`trident_id`, `shell`.`REC`, `shell`.`Pre_Scope`, `shell`.`Post_Scope`, `shell`.`Entitlement`, `shell`.`PWO`, `shell`.`OTB`, `shell`.`Final_Design`, `shell`.`Revised_Final_Design`, `shell`.`Final_Power`
                * 
                */
 
                DataRow[] stores = Schedules(storenum.ToString(), "*", StoreType.ToString(), ProjectStatus.Active);
                // for now get only the first returned row
                DataRow store = stores[0];

                string id = store["trident_id"].ToString();
                DataTable merchtable = ScheduleData.Tables["merch"];
                DataRow[] merchrows = merchtable.Select(string.Format("trident_id = '{0}'", id));
                if (merchrows.Length == 0)
                {
                    DataRow newrow = merchtable.NewRow();
                    newrow["trident_id"] = id;
                    FillRow(ref newrow);
                    merchtable.Rows.Add(newrow);
                }
                else
                {
                    DataRow merchrow = merchrows[0];
                    FillRow(ref merchrow);
                }


                UpdateSQLTable(ScheduleData.Tables["merch"].GetChanges(), "merch", "schedule");
                return true;
            }
            catch
            {
                return false;
            }
        }
        #endregion

        #region private Helper Methods
        private void FillRow(ref DataRow row)
        {
            if(!string.IsNullOrEmpty(PreId))
            row["Pre_PWO"] = row["Pre_PWO"].ToString() + PreId + ";";
            if (!string.IsNullOrEmpty(PwoId))
            row["PWO"] = row["PWO"].ToString() + PwoId + ";";
            if (!string.IsNullOrEmpty(OtpId))
            row["OTP"] = row["OTP"].ToString() + OtpId + ";";
            if (!string.IsNullOrEmpty(OtbId))
            row["OTB"] = row["OTB"].ToString() + OtbId + ";";
            if (!string.IsNullOrEmpty(FinalId))
            row["Final"] = row["Final"].ToString() + FinalId + ";";
            if (!string.IsNullOrEmpty(RevId))
            row["Revised"] = row["Revised"].ToString() + RevId + ";";
            if (!string.IsNullOrEmpty(ordercopy))
            row["Order_Copy"] = row["Order_Copy"].ToString() + ordercopy + ";";
            if (!string.IsNullOrEmpty(carpet))
            row["Carpet_Plan"] = row["Carpet_Plan"].ToString() + carpet + ";";
            if (!string.IsNullOrEmpty(power))
            row["Power_Plan"] = row["Power_PLan"].ToString() + power + ";";
        }

        private int parsenumber(string ToTest, string ToRemove)
        {
            int start = ToTest.IndexOf(ToRemove, StringComparison.CurrentCultureIgnoreCase);
            if (start != -1) ToTest = ToTest.Remove(start, ToRemove.Length);
            int num;
            if (int.TryParse(ToTest, out num)) return num;
            else return 0;
        }

        private string Test(string s, string split)
        {
            string t = string.Empty;
            string[] ta = s.Split(new string[] { split }, StringSplitOptions.RemoveEmptyEntries);
            if (ta.GetUpperBound(0) > 0)
            {
                t = ta[1];
                t = t.Trim();
            }
            return t;
        }

        private string DoString(string s)
        {
            string[] ta = s.Split(new char[] { ' ' });
            if (ta.GetUpperBound(0) > 0)
            {
                s = ta[0];
                if (s == "")
                {
                    s = ta[1];
                    s = s.Trim();
                    if (s != "")
                        return s;
                    else return string.Empty;
                }
                else return s;
            }
            else return string.Empty;
        }

       

        #endregion
    }
}
